/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hva.web.mvcwebapp.doa;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import nl.hva.web.mvcwebapp.models.Assignment;
import nl.hva.web.mvcwebapp.models.Test;
import nl.hva.web.mvcwebapp.models.Chapter;
import nl.hva.web.mvcwebapp.models.User;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.models.MadeAssignment;
import nl.hva.web.mvcwebapp.models.UserTest;
import nl.hva.web.mvcwebapp.models.UserTestPK;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 *
 * @author Thijs
 */
public class TestDAO {

    public TestDAO() {
    }

    public static List<Test> getAllTests(int chapter_id) {

        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Test.class);
        SessionFactory factory = config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("FROM Test WHERE chapter_chapterid='" + chapter_id + "'");

        List<Test> test_list = queryResult.list();
//        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//        Transaction tx = session.beginTransaction();
//        List<Chapter> chapter_list = session.createCriteria(Chapter.class).list();
        tx.commit();

        return test_list;
    }

    public static List<UserTest> getUserTest(int test_id, int user_id) {
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Test.class);
        SessionFactory factory = config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("FROM UserTest WHERE TEST_ID='" + test_id + "' AND USER_ID='" + 1 + "'");
        List<UserTest> test_list = queryResult.list();
        tx.commit();
        return test_list;
    }

    public static List<UserTest> getAllUserTest(int user_id) {
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Test.class);
        SessionFactory factory = config.configure().buildSessionFactory();
        Session session = factory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        Query queryResult = session.createQuery("FROM UserTest WHERE USER_ID='" + user_id + "'");
        List<UserTest> test_list = queryResult.list();
        tx.commit();
        return test_list;
    }

    public static Test getTest(int test_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        Test test = (Test) session.get(Test.class, test_id);
        tx.commit();

        //Course course = new Course(1, 1, "Java", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendiere ante, id porttitor ipsum semper non. Etiam mollis euismod dapibus. Phasellus vel turpis sem. Vestibulum dui ...", "1", "http://www.downloadstad.nl/screenshot/Java.jpg");
        return test;
    }

    public static ArrayList insertTest(HttpServletRequest request, Chapter chapter) {
        ArrayList validation_errors = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        Test test = getTestFromRequest(request, chapter, null);
        session.save(test);
        tx.commit();
        return validation_errors;
    }

    public static ArrayList insertTestForUser(HttpServletRequest request, Test test) {
        ArrayList validation_errors = new ArrayList();
        //int userid = Integer.valueOf("" + session_user.getAttribute("user_id"));
        HttpSession session_user = request.getSession(true);
        String firstname = (String) session_user.getAttribute("user_firstname");
        int user_id = 0;
        if (firstname != null) {
            user_id = Integer.valueOf("" + session_user.getAttribute("user_id"));
        }
        User user = UserDAO.getUser(user_id);
        UserTest testuser = new UserTest();
        UserTestPK pk = new UserTestPK();
        pk.setTest(test);
        pk.setUser(user);
        testuser.setPk(pk);

        ArrayList saved_answerlist = new ArrayList();

        String[] assignments = request.getParameterValues("assignment");
        boolean error = false;
        double max_score = 0;
        double score_gained = 0;
        double end_score = 0;
        for (int i = 0; i < assignments.length; i++) {
            int assignmentid = Integer.parseInt(request.getParameter("assignment_" + assignments[i]));
            Assignment assignment = AssignmentDAO.getAssignment(assignmentid);
            MadeAssignment madeassignment = new MadeAssignment();


            if (request.getParameter("answer_" + (i + 1)) != null && !request.getParameter("answer_" + (i + 1)).isEmpty()) {
                String[] answers = request.getParameterValues("answer_" + (i + 1));
                int score = 0;
                for (int j = 0; j < answers.length; j++) {
                    saved_answerlist.add(answers[j]);
                    if (assignment.getAssignmenttype() == 0) {
                        //check box
                        if (AssignmentDAO.getAnswer(Integer.parseInt(answers[j])).getAnswerright() == 1) {
                            score = score + 1;
                        } else {
                            score = score - 1;
                        }

                    } else {
                        //radio box
                        if (AssignmentDAO.getAnswer(Integer.parseInt(answers[j])).getAnswerright() == 1) {
                            score = score + 2;
                        }
                    }
                    System.out.println("Submit - Answer: " + answers[j] + " Assignment: " + assignments[i]);
                }
                if (score < 0) {
                    madeassignment.setRight(0);
                    madeassignment.setScore(0);
                    score = 0;
                } else if (score == 1) {
                    madeassignment.setRight(1);
                    madeassignment.setScore(1);
                } else if (score >= 2) {
                    madeassignment.setRight(2);
                    madeassignment.setScore(2);
                    score = 2;
                }

                //madeassignment.setAssignment(assignment);
                //madeassignment.setUsertest(testuser);
                //testuser.addMadeassignments(madeassignment);
                score_gained = score_gained + score;
                max_score = max_score + 2;
            } else {
                error = true;
                //Not all answers are filled in.
            }
        }


        if (!error) {
            System.out.println("MAX SCORE = " + max_score);
            System.out.println("SCORE GAINED = " + score_gained);
            end_score = (score_gained) / (max_score) * 100;
            int completed = 0;
            if (end_score > 55) {
                completed = 1;
            }
            System.out.println("COMPLETED = " + completed + " with SCORE = " + (int) end_score);

            //testuser.setChapter(test.getChapter());
            testuser.setCompleted(completed);
            testuser.setScore((int) end_score);
            try {
                Session session = HibernateUtil.getSessionFactory().getCurrentSession();
                Transaction tx = session.beginTransaction();
                session.save(testuser);
                tx.commit();
            } catch (Exception e) {

                e.printStackTrace();
            }
            return null;
        } else {
            return saved_answerlist;
        }
    }

    public static ArrayList updateTest(HttpServletRequest request, Test test) {
        ArrayList validation_errors = new ArrayList();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        Test updatedtest = getTestFromRequest(request, null, test);
        session.update(updatedtest);
        tx.commit();
        return validation_errors;
    }

    public static void deleteTest(int test_id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        Test temptest = (Test) session.load(Test.class, test_id);
        session.delete(temptest);
        tx.commit();
    }

    private static Test getTestFromRequest(HttpServletRequest request, Chapter chapter, Test test) {
        if (test == null) {
            test = new Test();
        }


        if (request.getParameter("testid") != null && !request.getParameter("testid").isEmpty()) {
            test.setTestid(Integer.parseInt(request.getParameter("testid")));
        }
        if (request.getParameter("testname") != null && !request.getParameter("testname").isEmpty()) {
            test.setTestname(request.getParameter("testname"));
        }
        if (request.getParameter("testdescription") != null && !request.getParameter("testdescription").isEmpty()) {
            test.setTestdescription(request.getParameter("testdescription"));
        }
        if (chapter != null) {
            test.setChapter(chapter);
        }
        return test;
    }
}
